﻿using System;
using System.Collections.Generic;
using System.Linq;
namespace PageAdmin.Utils
{

    /// <summary>
    /// 用于读取配置文件实体模型特性的类
    /// </summary>
    internal class ConfigFileAttributeHelper
    {
        /// <summary>
        /// 静态字典，用于保存配置文件路径
        /// </summary>
        private static Dictionary<string, string> _ConfigPathDictionary;

        static ConfigFileAttributeHelper()
        {
            _ConfigPathDictionary = new Dictionary<string, string>();
        }

        /// <summary>
        /// 获取ConfigReadAttribute特性的Path属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetConfigPath<T>() where T:class,new()
        {
            Type type = typeof(T);
            if (_ConfigPathDictionary.ContainsKey(type.FullName))
            {
                return _ConfigPathDictionary[type.FullName];
            }
            string configPath = type.Name;
            if (type.IsDefined(typeof(ConfigFileAttribute), false))
            {
                var attribute = type.GetCustomAttributes(typeof(ConfigFileAttribute), false).FirstOrDefault();
                Type attributeType = attribute.GetType();//获取当前的实例的类型
                configPath = attributeType.GetProperty("Path").GetValue(attribute).ToString();
            }
            if(string.IsNullOrEmpty(configPath))
            {
                return null;
            }
            //二次判断
            if (!_ConfigPathDictionary.ContainsKey(type.FullName))
            {
                _ConfigPathDictionary.Add(type.FullName, configPath);//加入到缓存字典中。
            }
            return configPath;
        }

    }

}
